import { ReqDepartmentListResponse, ReqDoctorResponse, ReqHospitalScheduleListResponse } from '@/api/hospitalList/hospitalList';
import type { DoctorList, ScheduleList, departmentItem, departmentList } from '@/api/hospitalList/model/hospitalListTypes';
import { Button, Card, Col, Empty, Pagination, Row, Skeleton, Tag, message } from 'antd'
import Table, { ColumnsType } from 'antd/lib/table';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { Key, useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom';

export default function HospitalSchedule() {

    //获取navigate 函数
    let navigate = useNavigate();

    //获取地址栏 params 参数
    let { hoscode } = useParams();

    //声明 当前页码
    let [current,setCurrent] = useState<number>(1);
    //声明每页展示数量
    let [pageSize,setPageSize] = useState<number>(5);
    //声明总数
    let [total,setTotal] = useState<number>(0);

    //声明 医院名称的状态
    let [hosname, setHosname] = useState<string>("");

    //声明 科室名称的状态
    let [depname, setDepname] = useState<string>("");

    //声明 排班日期的状态
    let [workDate, setWorkDate] = useState<string>("");

    // 声明 科室编号状态
    let [depcode, setDepcode] = useState<string>("");

    //声明科室状态
    let [department, setDepartment] = useState<departmentList>([]);

    //声明所有的一级科室 depcode 
    let [expandedKey, setExpandedKey] = useState<string[]>([]);


    //声明 排班规则的状态
    let [schedule, setSchedule] = useState<ScheduleList>([]);

    // 声明医生状态
    let [doctor, setDoctor] = useState<DoctorList>([]);

    //获取 左侧高度 
    let height = document.documentElement.clientHeight - 64 - 34 - 24 * 2 - 22 - 70;


    //表格 表头信息
    let columns: ColumnsType<any> = [
        {
            title: "序号",
            align: "center",
            render(text, row, index) {
                return index + 1;
            }
        },
        {
            title: "职称",
            align: "center",
            width: 120,
            dataIndex: "title"
        },
        {
            title: "号源时间",
            width: 140,
            align: "center",
            dataIndex: "workDate",
        },
        {
            title: "总预约数",
            align: "center",
            dataIndex: "reservedNumber",
        },
        {
            title: "剩余预约数",
            align: "center",
            dataIndex: "availableNumber",
        },
        {
            title: "挂号费(元)",
            align: "center",
            dataIndex: "amount",
        },
        {
            title: "擅长技能",
            align: "center",
            dataIndex: "skill"
        }
    ]


    //切换树结构的数据回调方法
    let changeTree = (selectedKeys: Key[], info: any) => {
        // console.log(info.node);
        //更新 医院科室名称和编号
        setDepcode(info.node.depcode);
        setDepname(info.node.depname);
       
    }

    //获取科室数据
    let getDepartmentList = async () => {
        //调用请求科室数据方法
        let result = await ReqDepartmentListResponse(hoscode as string);
        // console.log(result);

        //获取第一个一级科室的第一个二级科室编号
        let firstDepcode = (result[0].children as departmentItem[])[0].depcode;
        let firstDepname = (result[0].children as departmentItem[])[0].depname;
        //更新科室名称状态
        setDepname(firstDepname);
        //更新科室编号状态
        setDepcode(firstDepcode);

        // 为所有的一节科室添加disabled 禁用属性 
        let newresult = result.map(item => {
            item.disabled = true;
            return item;
        })

        //更新 科室状态
        setDepartment(newresult);

        //获取所有的一级科室的depcode
        let allDepcode = result.map(item => {
            return item.depcode;
        })
        //更新所有的一级科室 code
        setExpandedKey(allDepcode);




    }

    //获取排班规则的数据
    let getScheduleList = async () => {
        try {
            // 请求 科室排班规则的方法
            let ScheduleList = await ReqHospitalScheduleListResponse({
                page: current,
                limit: pageSize,
                hoscode: hoscode as string,
                depcode
            });

            //更新排班的状态
            setSchedule(ScheduleList.bookingScheduleList);
            //更新医院名称状态
            setHosname(ScheduleList.baseMap.hosname);
            //更新总数状态
            setTotal(ScheduleList.total);

            //获取第一个排班规则的日期
            let firstWorkData = ScheduleList.bookingScheduleList[0].workDate;
            //更新排班日期状态
            setWorkDate(firstWorkData);


           
        } catch (error) {
            //清空医生状态
            setDoctor([]);
            //清空 日期
            setWorkDate("");
            //提示
            message.error("失败！");
        }

    }

    // 获取 医生数据方法
    let getDoctor = async()=>{
         // 调用方法获取 医生数据
         let doctorList = await ReqDoctorResponse({
            hoscode: hoscode as string,
            depcode,
            workDate
        });

        //更新医生状态
        setDoctor(doctorList);
    }

    //切换排班日期方法
    let changeDoctor = (value:string) =>{
        return ()=>{
            //更新日期状态
            setWorkDate(value);
           
           
        }
    }


    //单独 模拟 componentDidMount
    //获取科室数据
    useEffect(() => {
        getDepartmentList();
    }, [])

    //获取排班规则的数据
    useEffect(() => {
        //初次进入组件，判断否存在depcode
        if(depcode){
            getScheduleList();
        }
    }, [depcode, depname,current,pageSize])

    //获取 医生数据
    useEffect(()=>{
        if(workDate) getDoctor();
    },[workDate])



    return (
        <Card>
            {/* 面包屑 */}
            <p>选择： {hosname} / {depname}  /  {workDate}</p>

            {/* 内容部分 */}
            <Row gutter={30}>
                {/* 左侧部分 */}
                <Col span={5}>
                    <div style={{ border: "1px solid #f0f0f0", height: height, overflow: "auto" }}>
                        <Tree
                            expandedKeys={expandedKey}
                            treeData={department as []}
                            // treeData={treeData}
                            fieldNames={{
                                title: "depname",
                                key: "depcode"
                            }}
                            selectedKeys={[depcode]}
                            onSelect={changeTree}
                        />
                    </div>
                </Col>
                {/* 右侧部分 */}
                {
                    schedule.length === 0 && doctor.length === 0 ? 
                    <Col span={19}><Empty /></Col>
                    :
                    <Col span={19}>
                    {/* 排班日期部分 */}
                    <div>
                        {
                            schedule.map(item => {
                                return <Tag onClick={changeDoctor(item.workDate)} style={{cursor:"pointer"}} key={item.workDate} color={workDate === item.workDate ? "green" : ""}>
                                    <div>{item.workDate} {item.dayOfWeek}</div>
                                    <div>{item.availableNumber} / {item.reservedNumber}</div>
                                </Tag>
                            })
                        }


                    </div>

                    {/* 分页部分 */}
                    <Pagination
                        className='mt'
                        current={current}
                        total={total}
                        pageSize={pageSize}
                        pageSizeOptions={[5, 10, 15, 20]}
                        showSizeChanger={true}
                        onChange={(page: number, pageSize: number)=>{
                            //更新页码和每页展示数量的状态
                            setCurrent(page);
                            setPageSize(pageSize);
                        }}
                    />

                    {/* 表格部分 */}
                    <Table
                        rowKey="id"
                        className='mt'
                        columns={columns}
                        dataSource={doctor}
                        bordered
                        pagination={false}
                    />


                    <Button onClick={() => {
                        navigate(-1);
                    }} className='mt' type="default">返回</Button>

                </Col>
                }
               



            </Row>

        </Card>
    )
}
